<?php

namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Http\Controllers\Controller;

use App\Library\Tools;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Configs;
use App\Models\User\UserLogin;
use App\Models\User\UserSession;
use App\Models\Validate\ValidBase;
use App\Models\video\DataCacheModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mews\Captcha\Captcha;
use Qcloud\Sms\SmsSingleSender;
use Validator;

class LoginController extends Controller
{
    public function __construct(){
        /*--- start 跨域测试用 (待删除) ---*/
        header('Access-Control-Allow-Origin: *');                                                                 // 允许任意域名发起的跨域请求
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        /*--- end 跨域测试用---*/
    }

    private $returnData = array(
        'code' => 0,
        'msg' => '请求成功',
        'data' => '',
    );

    public function rule(){
        return [
            'user_name' => 'required',
//            'user_name' => 'required|email',
            'user_pass' => 'required|regex:/^.{6,16}$/',
        ];
    }

    public function message(){
        return [
            'user_name.required' => '账号不能为空',
//            'user_name.email' => '账号格式错误',
            'user_pass.required' => '密码不能为空',
            'user_pass.regex' => '密码格式不正确,请输入6~16位的密码'
        ];
    }

    public function getCaptchaImg(Captcha $captchaBuilder){
        if ($this->returnData['code'] > 0){
            return response()->json($this->returnData);
        }
        $res = $captchaBuilder->create("flat", true);
        $this->returnData['data'] = $res;
        return response()->json($this->returnData);
    }

    public function login(Request $request, Captcha $captchaBuilder){
        //登陆之前去检测站点状态
        $con = Configs::query()->where("mall_id", $request->mallId && $request->mallId != "undefined" ? request()->mallId : 1)->first();
        $site_status = $con->site_status;
        $verify_arr = array(
            'user_name' => $request->username,
            'user_pass' => $request->password
        );
        if ($site_status == 0 && $verify_arr['user_name'] != 'root@admin.com'){
            $data['code'] = 1;
            $data['msg'] = '站点正在维护中，请等待片刻再尝试登陆';
            return response()->json($data);
        }
        $validator = Validator::make($verify_arr,$this->rule(),$this->message());//验证参数
        if ($validator->fails()) {
            $this->returnData['code'] = 103;
            $this->returnData['msg'] = $validator->errors()->all()[0];
            return response()->json($this->returnData);
        }
        $c = DataCacheModel::getValue("loginFail_{$request->username}");
        if ($request->imgCode && $request->imgKey) {
            if(!$captchaBuilder->check_api($request->imgCode, $request->imgKey)) {
                return ErrorCode::code('customized', "图片验证码错误");
            }
        }elseif($c){
            $this->returnData = ErrorCode::$admin_enum['account_error'];
            $this->returnData["data"] = ["activationImgCode" => true, "token" => null];
            return response()->json($this->returnData);
        }
        if($c >= 3) {
            return ErrorCode::code('customized', "密码输错3次，请等10分钟后再试");
        }
        $login_res = UserLogin::LoginAction($verify_arr);
        if($login_res['code'] != 0){
            DataCacheModel::saveCache(["key" => "loginFail_{$request->username}", "value" => !empty($c) ? $c + 1 : 1, "time" => 600]);
        }else{
            DataCacheModel::del("loginFail_{$request->username}_");
        }
        return response()->json($login_res);
    }

    public function qyWexin(Request $request){
        //登陆之前去检测站点状态
        $con = Configs::query()->where("mall_id", $request->mallId && $request->mallId != "undefined" ? request()->mallId : 1)->first();
        $site_status = $con->site_status;
        $verify_arr = array(
            'code' => $request->code,
        );
        if ($site_status == 0){
            $data['code'] = 1;
            $data['msg'] = '站点正在维护中，请等待片刻再尝试登陆';
            return response()->json($data);
        }
        $validator = Validator::make($verify_arr,['code' => 'required'],["code.required" => "code不能为空"]);//验证参数
        if ($validator->fails()) {
            $this->returnData['code'] = 103;
            $this->returnData['msg'] = $validator->errors()->all()[0];
            return response()->json($this->returnData);
        }
        $login_res = UserLogin::QyWexinAction($verify_arr);
        return response()->json($login_res);
    }

    public function logout(Request $request){
        $verify_arr = array(
            'token' => $request->token
        );
        $validModel = ValidBase::factory('ValidRule');
        $verify_res = $validModel->c_token($verify_arr);
        if($verify_res['code']>0){
            return response()->json($verify_res);
        }
        $login_res = UserLogin::LogoutAction($request->token);
        return response()->json($login_res);
    }

    //平台免登陆
    public function Nolandfall(Request $request){
        $wsToken = $request->post('wsToken','');
        $url = $request->post('wsDomain','');
        if ($wsToken == '' || $url == ''){
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = '错误登陆';
        }
        $url = urldecode($url);
        $res = Tools::curl($url."/web/home/getCheckToken", json_encode(["wsToken" => $wsToken]));
        $res = json_decode($res, 1);
        if($res["code"] == "0"){
            $userSessionModel = new UserSession();
            $session_id = $userSessionModel->setSession(['admin_id'=>1]);
            $this->returnData['data'] = ['token' => $session_id, "mallId" => 1];
        }else{
            $this->returnData['code'] = 1;
            $this->returnData["msg"] = "自动登录失败";
        }
        return response()->json($this->returnData);
    }

    //发送验证码
    public function sendCode(Request $request){
        $con = Configs::query()->where("mall_id", request()->mallData["id"])->first();
        $mobile = $request->post('mobile','');
        if(!$mobile){
            return ErrorCode::code("customized", "手机号不存在");
        }
        // 短信应用SDK AppID
        $appid = $con->sms_appid; // 1400开头
        // 短信应用SDK AppKey
        $appkey = $con->sms_appkey;
        // 需要发送短信的手机号码
        $phoneNumbers = [$mobile];
        //短信模版
        $templateId = $con->code_template ?: '296336';
        if (!AdminUser::query()->where(["name" => $mobile])->count() && !AdminUser::query()->where(["mobile" => $mobile])->count()){
            return ErrorCode::code("customized", "手机号未注册");
        }
        DB::beginTransaction();
        // 签名
        $smsSign = $con->sms_sign;
        // 指定模板ID单发短信
        $code = rand(1000, 9999);
        $validate_res = DB::table('verification')->where('mobile',$mobile)->where("mall_id", request()->mallData["id"])->first();
        $validate_res = json_decode(json_encode($validate_res),true);
        if ($validate_res){
            $info['code'] = $code;
            $info['create_time'] = time();
            $info['overdue_time'] = time() + 300;
            DB::table('verification')->where('mobile',$mobile)->update($info);
        }else{
            $info['mobile'] = $mobile;
            $info['code'] = $code;
            $info['create_time'] = time();
            $info['overdue_time'] = time() + 300;
            $info["mall_id"] = $request->mallData["id"];
            DB::table('verification')->insert($info);
        }
        try {
            $code_info = [$code];
            if ($this->sendSms($templateId, $code_info, $phoneNumbers[0], "86", $msg, [
                "smsId" => $appid, 'smsSecret' => $appkey, 'smsSign' => $smsSign ?: ''
            ])){
                DB::commit();
                return response()->json($this->returnData);
            }else{
                DB::rollback();
                return ErrorCode::code("customized", $msg);
            }
        } catch(\Exception $e) {
            DB::rollback();
            return ErrorCode::code("customized", $e->getMessage().$e->getTraceAsString());
        }
    }

    public function sendSms($templateId, $data, $mobile, $prefix = "86", &$msg = '', $smsConfig = null)
    {
        $random = rand(1000, 9999);
        $time = time();
        $url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid=" . $smsConfig["smsId"] . "&random=" . $random;
        $sig = hash('sha256', 'appkey=' . $smsConfig["smsSecret"] . '&random=' . $random . '&time=' . $time . '&mobile=' . $mobile);
        $arr = array(
            "ext" => "",
            "extend" => "",
            "params" => $data,
            "sig" => $sig,
            "sign" => $smsConfig["smsSign"],
            "tel" => array(
                "mobile" => $mobile,
                "nationcode" => $prefix
            ),
            "time" => $time,
            "tpl_id" => $templateId,
        );
        $result = json_decode(Tools::curl($url, json_encode($arr, true)), true);
        if (!isset($result["result"]) || $result["result"] != '0') {
            $msg = !isset($result["result"]) ? $result["ErrorInfo"] : $result["errmsg"];
            return false;
        } else {
            return true;
        }
    }

    //验证用户输入的验证码
    public function checkVerification(Request $request){
        $mobile = $request->post('mobile','');
        $code = $request->post('code','');
        $res = DB::table('verification')->where('mobile',$mobile)->where("mall_id", request()->mallData["id"])->first();
        $res = json_decode(json_encode($res),true);
        if ($res['overdue_time'] < time()){
            return ErrorCode::code("customized", "验证码过期");
        }
        if ($res['code'] != $code){
            return ErrorCode::code("customized", "验证码错误");
        }else{
            return response()->json($this->returnData);
        }
    }

    //修改密码
    public function updatePassword(Request $request){
        $mobile = $request->post('mobile','');
        $new_passwoed = $request->post('password','');
        if(!$new_passwoed){
            return ErrorCode::code("customized", "密码不存在");
        }
        $res = AdminUser::query()->where("name", $mobile)->first();
        if (!$res && !$res = AdminUser::query()->where("mobile", $mobile)->first()){
            return ErrorCode::code("customized", "用户不存在");
        }
        $res = json_decode(json_encode($res),true);
        $where['password'] = bcrypt($new_passwoed);
        AdminUser::query()->where('id',$res['id'])->update($where);
        $this->returnData['msg'] = '修改密码成功';
        return response()->json($this->returnData);
    }
}
